package com.filldream.fastboot.common.annotation.validator;

import com.filldream.fastboot.common.annotation.SunParam;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * @author RickSun
 * @Description 自定义参数校验
 **/
public class SunValidator implements ConstraintValidator<SunParam, Object> {

    private  Pattern pattern ;
    private  boolean checkNull;

    @Override
    public void initialize(SunParam sunParam) {
        pattern = Pattern.compile(sunParam.value());
        checkNull = sunParam.checkNull();
    }

    /**
     * @author RickSun
     * @see org.springframework.util.ObjectUtils
     **/
    @Override
    public boolean isValid(Object obj, ConstraintValidatorContext constraintValidatorContext) {
        boolean isNull ;
        if( checkNull ){
            if (obj == null) {
                isNull = false;
            } else if (obj instanceof Optional) {
                isNull =  ((Optional)obj).isPresent();
            } else if (obj instanceof CharSequence) {
                isNull =  ((CharSequence)obj).length() != 0;
            } else if (obj.getClass().isArray()) {
                isNull =  Array.getLength(obj) != 0;
            } else if (obj instanceof Collection) {
                isNull =  !((Collection)obj).isEmpty();
            } else {
                isNull =  obj instanceof Map ? false : ((Map)obj).isEmpty() ;
            }
            if(isNull == false){
                constraintValidatorContext.disableDefaultConstraintViolation();//禁用默认的message的值
                //重新添加错误提示语句
                constraintValidatorContext
                        .buildConstraintViolationWithTemplate("参数不能为空-IsNotNull").addConstraintViolation();
                return false;
            }
        }

        if(StringUtils.isBlank(pattern.pattern())){
            return true;
        }

        boolean matches = pattern.matcher(obj.toString()).matches();
        return matches;
    }

}